<?php
include_once 'database/db.php';
include_once $_SERVER['DOCUMENT_ROOT']."/lib/spyc.php";
include_once 'cleanfile.php';
include_once 'security/token.php';
header('content-type:application/json;charset=utf-8');
@$fileName = $_POST['file_name'];            // 请求参数，加@符号，避免参数缺失造成错误的返回格式
@$total_blob_num = $_POST['total_blob_num']; // 请求参数
@$blobSize = $_POST['blob_size'];            // 请求参数
@$token = $_COOKIE['token'];                 // Token
@$fileSize = $_POST['file_size'];              // 文件大小
$data = [];

$ENV = spyc_load_file($_SERVER['DOCUMENT_ROOT'].'/properties/env.yml');
$host = ($ENV['upload']['host'])['0'];

if (!$token) {
    // token缺失
    $data['code']=-1;
    $data['msg']="非法请求,请重新访问: http://$host:92/launch.php";
} elseif (!$fileName || !$total_blob_num || !$blobSize || !$fileSize) {
    // 参数不完整
    $data['code']=0;
    $data['msg']='请求参数错误，请提供file_name参数';
} else {
    // 正常情况
    $tokenInstance = new Token();
    if ($tokenInstance->hasRightToUpload($token, $fileSize)) {
        $tokenInstance->update($token, $fileSize);
    } else {
        $data['code']=-1;
        $data['msg']='您24小时内上传的文件总大小已超过允许值(20G)';
        goto end;
    }

    // 1. 创建存储文件的文件夹
  $filepath = ($ENV['upload']['path'])['0'].DIRECTORY_SEPARATOR.sha1($fileName); //上传目录
  if (!file_exists($filepath)) {
      mkdir($filepath);
  }

    // 2. 在mongodb数据库存储相应文件信息
    $DB = new DB();
    $cursor = $DB->query('fileshare.files', ['id' => sha1($fileName)]);

    $fileCount = 0;
    foreach ($cursor as $document) {
        $fileCount++;
    }

    if ($fileCount) {
        $data['code']=0;
        $data['msg']='文件已存在，请更改文件名后重试';
        $data['downloadURL']='http://'.$host.':92/fileshare'.$filepath.DIRECTORY_SEPARATOR.$fileName;
    } else {
        // 清理过期文件
        $clean = new CleanFile();
        $clean->start();

        $res = $DB->insert('fileshare.files', ['fileName'=>$fileName,'totalBlobNum'=>$total_blob_num,'ctime'=>time(),'id'=>sha1($fileName),'valid'=>true,'lastBlobSize'=>0,'blobSize'=>$blobSize]);

        if ($res->getInsertedCount()) {
            $data['code']=1;
            $data['msg']='文件信息存储成功';
        } else {
            $data['code']=-1;
            $data['msg']='文件信息存储失败';
        }
    }
}

end:
echo json_encode($data);
